<template>
  <div class="VuexOne">
    <h3>当前和为: {{ sum }}</h3>
    <h3>当前和为: {{ bigSum }}</h3>
    <h3>学校为: {{ school }}</h3>
    <h3>学科为: {{ subject }}</h3>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd">当前求和为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>
import {mapState, mapGetters,mapActions} from "vuex";

export default {
  name: "VuexOne",
  data() {
    return {
      n: 1
    }
  },
  computed: {
    /* 获取state中值,第一种写法
    sum(){
      return this.$store.state.sum;
    },
    school(){
      return this.$store.state.school;
    },
    subject(){
      return this.$store.state.subject;
    },
    */
    /* 获取state中值,第二种写法
    ...mapState({sum:'sum',school:'school',subject:'subject'}),
   */
    /* 获取state中值,第一种写法*/
    ...mapState('count',['school', 'subject', 'sum']),

    /* 获取getters中值 第一种写法
    bigSum(){
      return this.$store.getters.bigSum
    },
     */
    /* 获取getters中值 第二种写法
    ...mapGetters({bigSum:'bigSum'})
     */
    /* 获取getters中值 第三种写法*/
    ...mapGetters('count',['bigSum'])
  },
  methods: {
    // increment() {
    //   this.$store.dispatch('increment', this.n)
    // },
    // decrement() {
    //   this.$store.dispatch('decrement', this.n)
    // },
    ...mapActions('count',["increment","decrement"]),
    incrementOdd() {
      if (this.$store.state.count.sum % 2) {
        this.$store.commit('count/INCREMENT', this.n)
      }
    },
    incrementWait() {
      setTimeout(() => {
        this.$store.commit('count/INCREMENT', this.n)
      }, 500);
    }
  }
}
</script>

<style scoped lang="less">
.VuexOne {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;

  h3 {
    width: 100%;
  }

  select {
    width: 100px;
  }

  button {
    margin: 0 10px;
  }
}
</style>
